package com.share.template;

import com.share.domain.MyEmail;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import java.util.Date;

public class EmailTemplate {
    private JavaMailSender mailSender;

    public EmailTemplate(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendEmail(MyEmail email) {
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
            helper.setFrom(email.getFrom());
            helper.setTo(email.getTo());
            helper.setSubject(email.getSubject());
            helper.setText(email.getContent(), true);  // true 表示支持 HTML 格式

            if (email.getAttachment() != null) {
                helper.addAttachment("附件", new ByteArrayResource(email.getAttachment().getBytes()));
            }

            helper.setSentDate(new Date());
            mailSender.send(helper.getMimeMessage());
            System.out.println("邮件发送成功！");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("邮件发送失败：" + e.getMessage());
        }
    }
}
